import router from '@/router'

const digital = []
const zeroSpan = []
const harmonic = []

const get = () => {
  const { path } = router.currentRoute.value
  if (path.includes('digitalmodulation')) {
    return digital
  } else if (path.includes('harmonic')) {
    return harmonic
  } else {
    return zeroSpan
  }
}

const addInstance = (list, { name, instance }) => {
  const ite = list.find(item => item.name === name)
  if (ite) {
    return
  }
  list.push({ name, instance })
}

const set = (instance, name) => {
  const { path } = router.currentRoute.value
  if (path.includes('digitalmodulation')) {
    addInstance(digital, { name, instance })
  } else if (path.includes('harmonic')) {
    addInstance(harmonic, { name, instance })
  } else {
    addInstance(zeroSpan, { name, instance })
  }
}

const del = name => {
  const { path } = router.currentRoute.value
  if (path.includes('digitalmodulation')) {
    remove(name, digital)
  } else if (path.includes('harmonic')) {
    remove(name, harmonic)
  } else {
    remove(name, zeroSpan)
  }
}

const query = async name => {
  const instances = get()
  const current = instances.find(item => item.name === name)
  if (current) {
    return current
  } else {
    await new Promise(resolve => setTimeout(() => resolve()))
    return instances.find(item => item.name === name) || {}
  }
}

const remove = (name, list) => {
  const index = list.findIndex(item => item.name === name)
  if (index > -1) {
    list.splice(index, 1)
  }
}

export default { get, set, del, query }
